#include "backgammon.h"

void InitBoard(char board[ROW][COL]){
    int i = 0;
    for (i = 0; i < ROW; i++){
        int j = 0;
        for (j = 0; j < COL; j++){
            board[i][j] = ' ';
        }
    }
}

void PrintBoard(char board[ROW][COL]){
    int i = 0;
    for ( i = 0; i < ROW; i++){
        int j = 0;
        //打印空白符和'|'
        for(j = 0; j < COL; j++){
            printf(" %c ", board[i][j]);
            if (j < COL - 1)
                printf("|");            
        }
        printf("\n");
        //打印分割线
        if( i < ROW - 1){
            for(j = 0; j < COL; j++){
            printf("---");
            if( j < COL - 1)
                printf("|");            
        }
        printf("\n");
        }        
    }
}

void Playermove(char board[ROW][COL]){
    int x = 0;
    int y = 0;
    printf("玩家下\n");
    while(1){
        x = 0;
        y = 0;
        printf("请输入坐标:>");
        scanf("%d %d", &x, &y);

        if( x >= 1 && x <= ROW && y >= 1 && y <= COL){
            //判断是否占用
            if (board[x - 1][y - 1] != ' '){
                printf("此位置已被选择，请重新输入\n");
            }
            else {
                board[x - 1][y - 1] = '*';
                break;
                } 
        }
        else 
            printf("坐标非法，请重新输入\n");            
    }
}

void Computermove(char board[ROW][COL]){
    printf("电脑下\n");
    while(1){
        int x = rand() % ROW;
        int y = rand() % COL;
        
        //判断占用
        if(board[x][y] == ' '){
            board[x][y] = '#';
            break;
        }
    }
}

//返回1为满
//返回-1为空
int IsFullboard(char board[ROW][COL]){
    for(int i = 0; i < ROW; i++)
        for(int j = 0; j < COL; j++){
            if(board[i][j] == ' ')
                return -1;
        }
    return 1;
}

char Iswin(char board[ROW][COL]){
    int flag = 0;

    //主对角线
    for (int i = 0; i < ROW - 1; i++){
        if (board[i][i] != board[i + 1][i + 1] || board[i][i] == ' ')
            break;
        if ((ROW - 1) == (i + 1))
            return board[0][0];
            
    }


    //副对角线
    for (int i = 0; i < ROW - 1; i++){
        if (board[i][COL -1 - i] != board[i + 1][COL - i - 2] || board[i][COL - 1 - i] == ' ')
            break;
        if ((ROW - 1) == (i + 1))
            return board[0][COL - 1];           
    }

    //每行
    for (int i = 0; i < ROW; i++){
        for (int j = 0; j < COL - 1; j++){
            if (board[i][j] != board[i][j + 1] || board[i][j] == ' ')
                break;
            if ((COL - 1) == (j + 1))
                return board[i][0];
        }
    }

    //每列
    for (int j = 0; j < COL; j++){
        for (int i = 0; i < ROW - 1; i++){
            if (board[i][j] != board[i + 1][j] || board[i][j] == ' ')
                break;
            if ((ROW - 1) == (i + 1))
                return board[0][j];
        }
    }

    int ret = IsFullboard(board);
    if (1 == ret) return 'D';
    else return 'C';
}